package com.unis.iptv.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TitleTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.visitors.HtmlPage;

public class HtmlParser {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String uri = "http://58.223.251.139:8298/auth/dfsafdas";

		String regex = "(http://.*/)[^/]*";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(uri);
		if (m.find())
			System.out.println(m.group(1));
		
		
		//		DefaultHttpClient httpClient =new DefaultHttpClient();
//		HttpGet httpGet=new HttpGet("http://www.baidu.com");
//		HttpResponse response=httpClient.execute(httpGet);
//		HttpEntity entity=response.getEntity();
//		String content=EntityUtils.toString(entity);
//				
//		System.out.println(content);
//		readByHtml(content);
//		readTextAndLinkAndTitle(content);
	}
	/**
     * 按页面方式处理.解析标准的html页面
     * @param content 网页的内容
     * @throws Exception
     */
    public static void readByHtml(String content) throws Exception {
        Parser myParser;
        myParser = Parser.createParser(content, "utf8");
        HtmlPage visitor = new HtmlPage(myParser);
        myParser.visitAllNodesWith(visitor);

        String textInPage = visitor.getTitle();
        System.out.println(textInPage);
        NodeList nodelist;
        nodelist = visitor.getBody();
        
        System.out.print(nodelist.asString().trim());
    }

    /**
     * 分别读纯文本和链接.
     * @param result 网页的内容
     * @throws Exception
     */
	public static void readTextAndLinkAndTitle(String result) throws Exception {
        Parser parser;
        NodeList nodelist;
        parser = Parser.createParser(result, "utf8");
        NodeFilter textFilter = new NodeClassFilter(TextNode.class);
        NodeFilter linkFilter = new NodeClassFilter(LinkTag.class);
        NodeFilter titleFilter = new NodeClassFilter(TitleTag.class);
        OrFilter lastFilter = new OrFilter();
        lastFilter.setPredicates(new NodeFilter[] { textFilter, linkFilter, titleFilter });
        nodelist = parser.parse(lastFilter);
        Node[] nodes = nodelist.toNodeArray();
        String line = "";
        
        for (int i = 0; i < nodes.length; i++) {
            Node node = nodes[i];
            if (node instanceof TextNode) {
                TextNode textnode = (TextNode) node;
                line = textnode.getText();
            } else if (node instanceof LinkTag) {
                LinkTag link = (LinkTag) node;
                line = link.getLink();
            } else if (node instanceof TitleTag) {
                TitleTag titlenode = (TitleTag) node;
                line = titlenode.getTitle();
            }
            
            if (isTrimEmpty(line))
                continue;
            System.out.println(line);
        }
    }
	
	/**
     * 去掉左右空格后字符串是否为空
     */
    public static boolean isTrimEmpty(String astr) {
        if ((null == astr) || (astr.length() == 0)) {
            return true;
        }
        if (isBlank(astr.trim())) {
            return true;
        }
        return false;
    }

    /**
     * 字符串是否为空:null或者长度为0.
     */
    public static boolean isBlank(String astr) {
        if ((null == astr) || (astr.length() == 0)) {
            return true;
        } else {
            return false;
        }
    }
    
    
//    请问一下，怎样将修改过得html保存到文件中
//    code如下
//    static void saveFile(){Parser parser = new Parser(getContentByLocalFile(file));
//    NodeFilter nt = new NodeClassFilter(ImageTag.class) ;
//    NodeList tmpImageList = (NodeList) parser.parse(nt);
//
//    /*linkTmpHash = new Hashtable();
//    for (int i = 0; i < length; i++) {
//    Element tmpElement = (Element) tmpNodeList.item(i);
//    String href = tmpElement.getAttribute("href");
//    if (href != null && !href.equals("")) {
//    linkTmpHash.put(href, "");
//    }
//    }
//    data.setHrefs((String[]) linkTmpHash.keySet().toArray(new String[linkTmpHash.size()]));*/
//    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (file)));
//    linkTmpHash = new Hashtable();
//    for (int i = 0; i < tmpImageList.size(); i++) {
//    imgnode = (ImageTag)tmpImageList.elementAt(i);
//    String src = imgnode.getImageURL();
//    if (URLPathNameUtil.isAbsolutePath(src)) {
//    if (testAbsolutePath) {
//    testImagetag(file,src);
//    }
//    } else {
//    if (testRelativePath) {
//    testImagetag(file, src);
//    }
//    }
//    if(getRealPath()!=null){
//    imgnode.setImageURL(getRealPath());
//    writer.write(tmpImageList.toHtml());
//    }
//    /*if (src != null && !src.equals("")) {
//    linkTmpHash.put(src, "");
//    }*/
//    }
//    writer.flush();
//    writer.close ();
//}
}
